<template>
  <Layout>
    <div class="user-management max-width-1500">
      <div class="header">
        <h2>用户管理</h2>
        <div class="header-actions">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索用户账号或名称"
            style="width: 200px; margin-right: 10px;"
            clearable
            @clear="fetchUserList"
            @keydown.enter="fetchUserList"
          >
            <template #append>
              <el-button :icon="Search" @click="fetchUserList" />
            </template>
          </el-input>
          <el-button type="primary" @click="handleAddUser" style="margin-left: 10px;">新增用户</el-button>
          <el-button type="success" @click="fetchUserList" :loading="loading">刷新</el-button>
          <el-button
              type="danger"
              @click="handleBatchDelete"
              :disabled="selectedUsers.length === 0"
          >
            批量删除({{ selectedUsers.length }})
          </el-button>
        </div>
      </div>
      
      <div class="table-container">
        <el-table
          :data="userList"
          style="width: 100%"
          v-loading="loading"
          element-loading-text="加载中..."
          @selection-change="handleSelectionChange"
          @sort-change="handleSortChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="user_id" label="用户ID" width="100" sortable />
          <el-table-column label="头像" width="80">
            <template #default="scope">
              <el-avatar 
                :size="40" 
                :src="scope.row.avatar"
              >
                {{ scope.row.name?.charAt(0) }}
              </el-avatar>
            </template>
          </el-table-column>
          <el-table-column prop="account" label="账号" width="150" sortable />
          <el-table-column prop="name" label="名称" width="120" sortable />
          <el-table-column prop="signature" label="个性签名" show-overflow-tooltip />
          <el-table-column prop="role" label="角色" width="100">
            <template #default="scope">
              <el-tag v-if="scope.row.role === 'admin'">管理员</el-tag>
              <el-tag type="info" v-else>普通用户</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="创建时间" width="180" sortable>
            <template #default="scope">
              {{ formatDate(scope.row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button size="small" @click="handleEditUser(scope.row)">编辑</el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="handleDeleteUser(scope.row)"
                :loading="deletingUserId === scope.row.user_id"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.limit"
          :page-sizes="[50, 500, 1000]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      
      <!-- 用户编辑/新增弹窗 -->
      <el-dialog
        v-model="dialogVisible"
        :title="editingUser ? '编辑用户' : '新增用户'"
        width="500px"
        :before-close="handleDialogClose"
      >
        <UserProfileForm
          v-model="form"
          :is-create="!editingUser"
          @success="handleFormSuccess"
          @error="handleFormError"
        />
      </el-dialog>
    </div>
  </Layout>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import Layout from '@/components/Layout.vue'
import UserProfileForm from '@/components/UserProfileForm.vue'
import type { User } from '@/api/modules/user'
import { getUserListPage, deleteUser, batchDeleteUser } from '@/api/modules/user'

// 用户列表
const userList = ref<User[]>([])

// 加载状态
const loading = ref(false)

// 删除用户时的加载状态
const deletingUserId = ref<number | null>(null)

// 选中的用户
const selectedUsers = ref<User[]>([])

// 搜索关键词
const searchKeyword = ref('')

// 排序字段
const sortField = ref('createdAt')

// 排序方式
const sortOrder = ref('DESC')

// 弹窗相关
const dialogVisible = ref(false)
const editingUser = ref<User | null>(null)
const form = ref<Partial<User> | null>(null)

// 分页信息
const pagination = ref({
  page: 1,
  limit: 50,
  total: 0
})

// 格式化日期
const formatDate = (dateString: string | undefined) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN');
};

// 处理排序变化
const handleSortChange = (sort: { column: any; prop: string; order: string }) => {
  if (sort.prop) {
    sortField.value = sort.prop;
    sortOrder.value = sort.order === 'ascending' ? 'ASC' : 'DESC';
  } else {
    sortField.value = 'createdAt';
    sortOrder.value = 'DESC';
  }
  fetchUserList();
};

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  try {
    const response = await getUserListPage({
      page: pagination.value.page,
      limit: pagination.value.limit,
      keyword: searchKeyword.value || undefined,
      sort_field: sortField.value,
      sort_order: sortOrder.value
    })
    
    userList.value = response.data?.list || []
    pagination.value.total = response.data?.pagination?.total || 0
  } catch (error) {
    console.error('获取用户列表失败:', error)
    // 错误信息已经在request.ts的响应拦截器中处理过了，这里不需要再显示
  } finally {
    loading.value = false
  }
}

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  pagination.value.limit = val
  pagination.value.page = 1 // 重置到第一页
  fetchUserList()
}

// 处理当前页变化
const handleCurrentChange = (val: number) => {
  pagination.value.page = val
  fetchUserList()
}

// 处理选择变化
const handleSelectionChange = (val: User[]) => {
  selectedUsers.value = val
}

// 处理新增用户
const handleAddUser = () => {
  editingUser.value = null
  // 每次新增用户时都提供一个空的表单对象，避免保留之前的信息
  form.value = {
    user_id: undefined,
    account: '',
    password: '',
    name: '',
    signature: '',
    avatar: '',
    avatar_upload_id: null,
    role: undefined
  }
  dialogVisible.value = true
}

// 处理编辑用户
const handleEditUser = (user: User) => {
  editingUser.value = user
  form.value = { ...user }
  dialogVisible.value = true
}

// 处理删除用户
const handleDeleteUser = async (user: User) => {
  ElMessageBox.confirm(
    `确定要删除用户 "${user.name}" 吗？此操作不可恢复！`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(async () => {
    if (!user.user_id) return
    
    deletingUserId.value = user.user_id
    try {
      await deleteUser(user.user_id)
      ElMessage.success('删除成功')
      // 重新获取用户列表
      fetchUserList()
    } catch (error) {
      console.error('删除用户失败:', error)
      // 错误信息已经在request.ts的响应拦截器中处理过了，这里不需要再显示
    } finally {
      deletingUserId.value = null
    }
  })
  .catch(() => {
    // 用户取消删除
  })
}

// 处理批量删除用户
const handleBatchDelete = async () => {
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedUsers.value.length} 个用户吗？此操作不可恢复！`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(async () => {
    try {
      const userIds = selectedUsers.value.map(user => user.user_id!).filter(id => id !== undefined);
      if (userIds.length === 0) {
        ElMessage.warning('请选择有效的用户进行删除');
        return;
      }
      
      const response = await batchDeleteUser(userIds);
      ElMessage.success(response.data?.msg);
      // 清空选中项
      selectedUsers.value = [];
      // 重新获取用户列表
      await fetchUserList();
    } catch (error) {
      console.error('批量删除用户失败:', error);
      // 错误信息已经在request.ts的响应拦截器中处理过了，这里不需要再显示
    }
  })
  .catch(() => {
    // 用户取消删除
  })
}

// 处理弹窗关闭
const handleDialogClose = () => {
  // 清除表单中的密码信息
  if (form.value) {
    form.value.password = ''
  }
  dialogVisible.value = false
}

// 处理表单提交成功
const handleFormSuccess = (user: User) => {
  // 移除了重复的成功提示，只保留刷新列表操作
  dialogVisible.value = false
  // 重新获取用户列表
  fetchUserList()
}

// 处理表单提交失败
const handleFormError = (error: any) => {
  console.error('表单提交失败:', error)
  // 错误信息已经在request.ts的响应拦截器中处理过了，这里不需要再显示
}

// 组件挂载时获取用户列表
onMounted(() => {
  fetchUserList()
})
</script>

<style scoped>
.user-management {
  padding: 20px;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  height: 100%;
  overflow: auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  align-items: center;
}

.table-container {
    height: calc(100% - 150px);
  overflow: auto;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>